<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Warehouse_model extends MY_Model {

	var $table = 'sm_warehouse_stock';
	
	//构造函数
	public function __construct() {
		//调用父类构造函数，必不可少
		parent::__construct();
	}
	/**
	 * 取得所有供货商库存
	 * @param array $config
	 * @param array $like
	 * @return array
	 */
	public function getWarehouse($config = array(), $like = array()) {
		$config['totalCount'] = $this->get_search_num(NULL, $like);
		if($config['offset'] >= $config['totalCount']) {
			$config['offset'] = 0;
			$config['pageNum'] = 1;
		}
		$data = $config;
		$config['join'][] = array('product p', $this->table . '.product_id=p.id', 'left');
		$config['join'][] = array('album al', 'p.thumbnail_id=al.id', 'left');
		$config['join'][] = array('areas_enabled ae', $this->table . '.address_id=ae.id', 'left');
		$config['join'][] = array('areas a', 'ae.district_id=a.id', 'left');
		$config['select'] = $this->table . '.*,p.name,al.img,ae.address,a.description';
		$data['data'] = $this->search(NULL, $config, $like);
		return $data;
	}
	/**
	 * 添加供货商库存
	 * @param array $ddata
	 * @return boolean
	 */
	public function addStock($data)
	{	
		try {
			$this->db->trans_begin();
			foreach ($data as $v) {
				$this->db->set('stock', "stock-{$v['request_num']}", false);
				$this->db->where(array('id'=>$v['product_id'], 'stock >='=>$v['request_num']));
				$this->db->update('product');
				$num = $this->db->affected_rows();
				if($num < 1) {
					throw new Exception('stock not enough');
				}
				$this->db->set('stock', "stock+{$v['request_num']}", false);
				$this->db->where(array('product_id'=>$v['product_id'], 'address_id'=>$v['address_id']));
				$this->db->update($this->table);
				$num = $this->db->affected_rows();
				if($num < 1) {
					$dataInsert = array(
						'product_id' => $v['product_id'],
						'address_id' => $v['address_id'],
						'stock' => $v['request_num'],
						'updated_at' => time()
					);
					$res = $this->db->insert($this->table, $dataInsert);	
					if(!$res) {
						throw new Exception('Syntax error');
					} 
				}
								
			}
			$this->db->trans_commit();
			return true;
		} catch (Exception $e) {
			$this->db->trans_rollBack();
			return false;
		}		
	}
}

